﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace SmartCity.ProcessEngine.Infrastructure.Extention
{
    /// <summary>
    /// jwt扩展静态类
    /// </summary>
    public static class JwtExtention
    {
        /// <summary>
        /// 注册jwt的扩展静态方法
        /// </summary>
        /// <param name="services">只能是  IServiceCollection servers对象才能调用jwt</param>
        /// <returns></returns>
        public static IServiceCollection AddJwt(this IServiceCollection services)
        {

            //授权认证（使用JWT）
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
            {
                // 私钥
                var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    // 验证发布者
                    ValidateIssuer = true,
                    // 发布者信息
                    ValidIssuer = "BeiJingBW",

                    // 验证接收者
                    ValidateAudience = true,
                    // 接收者
                    ValidAudience = "BeiJingBW",

                    // 验证是否过期
                    ValidateLifetime = true,

                    // 验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)

                };
            });
            // 配置Swagger
            services.AddSwaggerGen(o =>
            {
                // 显示 授权信息
                o.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Description = "添加JWT授权Token：Bearer Token值",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                o.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[]
            {

            }
        }
    });
            });

            return services;
        }






        /// <summary>
        /// 生成jwttoken令牌的公共方法
        /// </summary>
        /// <param name="accountName"></param>
        /// <param name="realName"></param>
        /// <param name="roleName"></param>
        /// <returns></returns>
        public static string CreateTokenString(string accountName, string realName, string roleName)
        {
            //放到载荷里的声明
            var claims = new Claim[] {
                new Claim("accountName", accountName),
                new Claim("realName", realName),
                new Claim("roleName", roleName)
            };
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials,
                claims: claims
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
